<?php
// $Id: waimai.php 433 2012-06-05 23:39:56Z tomqin@gmail.com $

defined('IN_ADMIN') or exit('Access Denied!');

class Waimai_Action extends Action_Admin{

    public function init(){
        parent::init();
        $this->shop_id = intval($this->params);
        $this->setVar('shop_id', $this->shop_id);

        $this->waimai = App::module('table_waimai', 'table', array($this->user));
        if(!$this->waimai->check_user_right($this->shop_id)){
            $this->renderDialog('您无权管理此商铺信息！');
        }
    }

    public function onModify(){
        $this->setVar('show_validator', 1);

        $data = $this->waimai->get_data($this->shop_id);
        if(empty($data)){
            $data['shop_id'] = $this->shop_id;
        }
        $this->setVar('data', $data);
        $this->render('admin/waimai/edit');
    }

    public function onDeliver(){
        $cityid  = $this->cityid;
        $zone    = App::module('zone', '', array($this->cityid));
        $deliver = Db::getKeyArray("SELECT zone_id, all_zone FROM `biz_waimai_deliver` WHERE `shop_id` = '{$this->shop_id}'", 'zone_id', 'all_zone');

        $this->setVar('zone', $zone);
        $this->setVar('deliver', $deliver);
        $this->render('/admin/waimai/deliver');
    }

    public function onSave(){
        if(array_get_bool($_POST, 'dosubmit')){
            $method  = array_get_string($_POST, 'method');
            if(in_array($method, array('modify', 'create'))){
                $_POST['delivery_time'] = $this->timeSpan($_POST['delivery_time'], 0, 1).' '.$this->timeSpan($_POST['delivery_time'], 2, 3);
            }
            switch($method){
                case 'modify':
                    $this->waimai->update($this->shop_id, $_POST);
                    $this->renderDialog('修改成功！', '/admin/waimai/modify/'.$this->shop_id);
                break;
                case 'deliver':
                    $this->waimai->replace_deliver($this->shop_id, $_POST);
                    $this->renderDialog('修改成功！', '/admin/waimai/deliver/'.$this->shop_id, 'deliver');
                break;
            }
        }else{
            $this->renderDialog('无效的参数！');
        }
    }

    private function timeSpan(array $post, $t1, $t2){
        $t1 = array_get_string($post, $t1);
        $t2 = array_get_string($post, $t2);
        if($t1 && $t2){
            if($t1 > $t2){$t=$t1;$t1=$t2;$t2=$t;}
            return "{$t1}-{$t2}";
        }else{
            return "";
        }
    }

    function __destruct(){}
}
?>